package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    //引入自动审核业务的接口
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    /**
     * 文章列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //参数校验
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //执行分页
        IPage<WmNews> ipage = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();

        //状态
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //发布时间
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }
        //关键字
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //当前用户
        queryWrapper.eq(WmNews::getUserId, WmThreadLocal.getWmUser().getId());

        ipage=  page(ipage,queryWrapper);
        //封装数据
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) ipage.getTotal());
        result.setData(ipage.getRecords());

        //返回数据

        return result;
    }

    /**
     * 文章发布，保存，修稿草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto){
        //1、参数校验
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //自动
        if(dto.getType()==-1){
            dto.setType(null);
        }


        //2.修改和保存的方法
        WmNews wmnews=new WmNews();
        BeanUtils.copyProperties(dto,wmnews);
        //封装数据userid
        wmnews.setUserId(WmThreadLocal.getWmUser().getId());
        wmnews.setCreatedTime(new Date());
        //解决格式
        List<String> images = dto.getImages();
        if(images.size()>0 && images!=null){
            String image = StringUtils.join(images, ",");
            wmnews.setImages(image);
        }
        saveOrUpdateWnews(wmnews);


        //3. 判断是否为草稿，如果为草稿，则以下步骤不再执行
        if(dto.getStatus()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.CAOGAO_EXIST);
        }


        //3.5 把内容中content里面的图片给抽取出来
        List<String>imageList= chouquImageList(wmnews);

        //4.关联内容中的图片与文章的关系，操作wm_news_marterial表，批量新增中间表
        //4.2 要把图片地址集合转化成地址所对应的素材id,根据图片地址去查询wm_material表从而获取对应的素材id
        contentImageToNews(wmnews,imageList, 0);

        //5.关联封面中的图片与文章的关系，操作wm_news_marterial表
        //5.1 判断封面是否是自动
        //返回值一定此时是空的
        fengmianImageToNews(dto, wmnews, imageList);
        //异步调用
        wmNewsAutoScanService.autoScanWmNews(wmnews.getId());

        return ResponseResult.okResult("发布成功");
    }

    /**
     * 封面图片与文章的关系
     * @param dto
     * @param wmnews
     * @param imageList
     */
    private void fengmianImageToNews(WmNewsDto dto, WmNews wmnews, List<String> imageList) {
        List<String> fengminaImages = dto.getImages();
        if(dto.getType()==null){

            //内容中的图片个数大于等于1小于3，此时我们认为是单图
            if(imageList.size()>=1 && imageList.size()<3){
                fengminaImages = imageList.stream().limit(1).collect(Collectors.toList());
                wmnews.setType((short) 1);
            }
            else  if(imageList.size()>=3){//多图
                fengminaImages= imageList.stream().limit(3).collect(Collectors.toList());
                wmnews.setType((short) 3);
            }else{//内容中也没有图片，我们认为无图
                wmnews.setType((short) 0);
            }
            wmnews.setImages(StringUtils.join(fengminaImages,","));
            updateById(wmnews);
        }
        //批量新增中间表
        contentImageToNews(wmnews,fengminaImages,1);
    }

    /**
     * 抽取的方法三，内容图片与文章的关系
     * @param wmnews
     * @param imageList
     * @param type
     */
    private void contentImageToNews(WmNews wmnews, List<String> imageList,Integer type) {
        if(imageList.size()>0 && imageList !=null){
            //根据图片地址集合获取素材集合
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //stream流获取素材id集合
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //4.1 调用mapper接口
            wmNewsMaterialMapper.saveBatch(materialIds, wmnews.getId(),type);
        }
    }
    /**
     * 抽取的第二个方法，获取文本内容中的图片地址集合
     * @param wmnews
     * @return
     */
    private List chouquImageList(WmNews wmnews) {
        List<String> imageUrlList=new ArrayList<>();


        //1.获取内容
        String content = wmnews.getContent();
        //2.转化类型格式，list嵌套map格式
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //3.从map中获取type=image的value值
        for (Map map : mapList) {
            if(map.get("type").equals("image")){//就是图片
                String imageUrl = (String) map.get("value");
                imageUrlList.add(imageUrl);
            }
        }
        return imageUrlList;

    }
    /**
     * 抽取的第一个方法。修改和保存文章。
     * @param wmNews
     */
    private void saveOrUpdateWnews(WmNews wmNews) {
        //修改
        if(wmNews.getId()!=null){
            //删除中间表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //修改文章表
            updateById(wmNews);
        }else{
            //新增
            save(wmNews);
        }
    }
}
